package cfg

import (
	"fmt"
	"gitee.com/whilew/gmodel/internal/util"
	"os"
	"path/filepath"
	"strings"
)

type EnvVar struct {
	G     bool
	Name  string
	Value string
}

func EnvFile(g bool) (string, error) {
	dir, err := os.UserConfigDir()
	if err != nil {
		return "", err
	}
	if dir == "" {
		return "", fmt.Errorf("missing user-config dir")
	}
	proj, err := util.GetProjRootDir()
	if err != nil {
		return "", err
	}
	if proj == "" || g {
		proj = "gmodel"
	} else {
		proj = util.MD5(proj)
	}
	return filepath.Join(dir, "gmodel/env", proj), nil
}

func getEnvFile(path string) (map[string]string, error) {
	data, err := os.ReadFile(path)
	if err != nil && (!os.IsNotExist(err)) {
		panic(fmt.Sprintf("gmodel: reading gmodel env config: %v", err))
	}

	lines := strings.Split(string(data), "\n")
	if lines[len(lines)-1] == "" {
		lines = lines[:len(lines)-1]
	}

	var envs = make(map[string]string)
	for _, line := range lines {
		i := strings.Index(line, "=")
		if i < 0 {
			panic(fmt.Sprintf("gmodel: arguments must be KEY=VALUE: invalid argument: %s", line))
		}
		envs[line[:i]] = line[i+1:]
	}
	return envs, nil
}
